<?php namespace App\Services;


use App\Repositories\JpushLogRepository;
use App\Repositories\JPushRepository;
use Illuminate\Support\Facades\Config;


class JpushService extends BaseService
{
	protected $JPushRepository;
	protected $JpushLogRepository;

	public function __construct(JPushRepository $JPushRepository, JpushLogRepository $JpushLogRepository)
	{
		$this->JPushRepository = $JPushRepository;
		$this->JpushLogRepository = $JpushLogRepository;
	}

	public function push($platform = 'all', $audience = 'all', $alert, $extras = [], $title = '')
	{
		/**
		 * 格式化参数
		 */
		if(is_array($audience)){
			if(isset($audience['alias']) && !is_array($audience['alias'])){
				//如果存在且不是数组,则format
				$audience['alias'] = [$audience['alias']];
			}
		}
		/**
		 * 获取参数
		 */
		$apns_production = Config::get('app.debug',true) ? 'false' : 'true';
		$cond = [
			'notification' => [
				"alert"   => $alert,
				"title"   => $title,
				"android" => [
					"extras" => $extras,
				],
				"ios"     => [
					'badge' => '+1',
					"extras" => $extras,
				],
			],
			"options"      => [
				'apns_production' => $apns_production,
			],
		];
		/**
		 * 商业逻辑
		 */
		$request = $this->JPushRepository->push($platform, $audience, $cond);
		$request = json_decode($request, true);
		/**
		 * 写日志
		 */
		$state = isset($request['error']) ? 2 : 1;
		//$this->JpushLogRepository->add_jpush_log($audience, $extras['notification_type'], $state, json_encode($extras), $alert);
		return $state;
	}

}